const jwt = require('jsonwebtoken');
const config = require('../config/environment');
const util = require('util');
const verify = util.promisify(jwt.verify);
const logger = require("../core/logger").getLogger("system");
const mysql = require('../core/mysql');
/**
 * 判断token是否可用
 */

function isContains(str, substr) {
    return str.indexOf(substr) >= 0;
}


module.exports = function () {
  return async function (ctx, next) {
      let {method, url, body} = ctx.request;

    try {
      // 获取jwt
      //   console.log(ctx.request);
        if (method.toLowerCase() !== 'options'){
            const token = ctx.header.authorization;
            if (token && !url.startsWith('/excel')) {
                try {
                    // 解密payload，获取用户名和ID
                    let payload = await verify(token.split(' ')[1], config.tokenSecret);
                    ctx.user = {
                        name: payload.name,
                        id: payload.id
                    };
                    logger.info("apiLog ", {req:{user_id:+payload.id,   method: method ,   url:url},
                        body: method === 'POST' ? JSON.stringify(body) : null});
                    let selectUser = await mysql.query(`SELECT manager_name FROM manager WHERE manager_id = ? `, payload.id);
                    if (selectUser.length <= 0){
                        ctx.status = 200;
                        ctx.body = {
                            result: 401,
                            message: '认证失败'
                        };
                        return;
                    }
                } catch (err) {
                    ctx.status = 200;
                    ctx.body = {
                        result: 401,
                        message: '认证失败'
                    };
                    return;
                }
            }
            await next();
        }else{
            ctx.status = 200;
            ctx.body = {
                result: 200,
                message: '认证成功'
            };
        }
    } catch (err) {
      if (!err || err === {}) return;
      if (err.status === 401) {
        ctx.status = 200;
        ctx.body = {
            result: 401,
          message: '认证失败'
        };
      } else {
        err.status = 200;
        ctx.body = {
            result: 404,
          message: '404 '+ err.toString()
        };
      }
    }
  }
}
